package com.yict.csms.resourceplan.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yict.common.entity.PageEntity;
import com.yict.common.service.impl.CommonService;
import com.yict.common.util.DateUtil;
import com.yict.csms.resourceplan.dao.impl.RtgcFlOrderDaoImpl;
import com.yict.csms.resourceplan.dao.impl.RtgcFlPlanAllDaoImpl;
import com.yict.csms.resourceplan.entity.RtgcFlOrder;
import com.yict.csms.resourceplan.entity.RtgcFlPlanAll;
import com.yict.csms.system.entity.DataDict;
import com.yict.csms.system.entity.Profession;
import com.yict.csms.system.entity.User;
import com.yict.csms.system.service.impl.CostServiceImpl;
import com.yict.csms.system.service.impl.DataDictServiceImpl;
import com.yict.csms.system.service.impl.ProfessionServiceImpl;
import com.yict.csms.system.util.DictionaryUtils;
import com.yict.csms.system.util.StringUtil;

@Service
public class RtgcFlOrderServiceImpl extends CommonService<RtgcFlOrder, Long> {

	@Autowired
	private RtgcFlPlanAllDaoImpl rtgcFlPlanAllDaoImpl;
	@Autowired
	private RtgcFlOrderDaoImpl rtgcFlOrderDaoImpl;
	@Autowired
	private DataDictServiceImpl dataDictService;
	@Autowired
	private CostServiceImpl costService;
	@Autowired
	private ProfessionServiceImpl professionService;

	public List<RtgcFlOrder> search(Map<String, Object> queryMap,
			PageEntity page) {
		pageEntity = new PageEntity();
		List<RtgcFlOrder> list = new ArrayList<RtgcFlOrder>();
		StringBuilder queryString = new StringBuilder();
		queryString.append("from RtgcFlOrder as c where 1=1");
		if (queryMap != null && queryMap.size() > 0) {
			if (queryMap.get("rtgcfldate") != null
					&& !"".equals(queryMap.get("rtgcfldate"))) {
				queryString
						.append(" and c.orderDate like to_date(:rtgcfldate,'yyyy-MM-dd')");
			}
			if (queryMap.get("companyId") != null
					&& !"".equals(queryMap.get("companyId"))) {
				Long companyId = Long.valueOf((String) queryMap
						.get("companyId"));
				queryMap.put("companyId", companyId);
				queryString.append(" and c.company.companyId =:companyId");
			}
			if (queryMap.get("opTypeId") != null
					&& !"".equals(queryMap.get("opTypeId"))) {
				queryString.append(" and c.machine.dictid =:opTypeId");
			}
			if (queryMap.get("rtgcFlTimeId") != null
					&& !"".equals(queryMap.get("rtgcFlTimeId"))) {
				queryString.append(" and c.orderTime.dictid =:rtgcFlTimeId");
			}
			queryString.append(" order by c.workBeginDate asc");
		}
		list = rtgcFlOrderDaoImpl
				.search(queryString.toString(), queryMap, page);
		pageEntity.setTotalRecord(rtgcFlOrderDaoImpl.getPageEntity()
				.getTotalRecord());
		return list;
	}

	public List<RtgcFlOrder> searchSure(Map<String, Object> queryMap,
			PageEntity page) {
		pageEntity = new PageEntity();
		List<RtgcFlOrder> list = new ArrayList<RtgcFlOrder>();
		StringBuilder queryString = new StringBuilder();
		queryString
				.append("from RtgcFlOrder as c where c.status.datacode != 'Fl_Plan_Status_1'");
		if (queryMap != null && queryMap.size() > 0) {
			if (queryMap.get("dateCode1") != null
					&& !"".equals(queryMap.get("dateCode1"))) {
				queryString
						.append(" and c.orderDate >= to_date(:dateCode1,'yyyy-MM-dd')");
			}
			if (queryMap.get("dateCode2") != null
					&& !"".equals(queryMap.get("dateCode2"))) {
				queryString
						.append(" and c.orderDate <= to_date(:dateCode2,'yyyy-MM-dd')");
			}
			if (queryMap.get("companyIds") != null
					&& !"".equals(queryMap.get("companyIds"))) {
				queryString.append(" and c.company.companyId in (:companyIds)");
			}
			if (queryMap.get("rtgcFlTimeCode") != null
					&& !"".equals(queryMap.get("rtgcFlTimeCode"))) {
				queryString.append(" and c.orderTime.dictid =:rtgcFlTimeCode");
			}
			if (queryMap.get("professionCode") != null
					&& !"".equals(queryMap.get("professionCode"))) {
				queryString.append(" and c.machine.dictid =:professionCode");
			}
			if (queryMap.get("statusCode") != null
					&& !"".equals(queryMap.get("statusCode"))) {
				queryString.append(" and c.status.dictid =:statusCode");
			}
		}
		list = rtgcFlOrderDaoImpl
				.search(queryString.toString(), queryMap, page);
		pageEntity.setTotalRecord(rtgcFlOrderDaoImpl.getPageEntity()
				.getTotalRecord());
		return list;
	}

	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	public boolean save(List<RtgcFlOrder> delList, List<RtgcFlOrder> list) {
		boolean bool = false;
		try {
			bool = rtgcFlOrderDaoImpl.remove(delList);
			for (RtgcFlOrder rtgcFlOrder : list) {
				bool = rtgcFlOrderDaoImpl.save(rtgcFlOrder);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return bool;
	}

	/**
	 * 派更提交
	 * 
	 * @param user
	 * @param delList
	 * @param list
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	public boolean commit(User user, List<RtgcFlOrder> delList,
			List<RtgcFlOrder> list) {
		boolean bool = false;
		try {
			bool = rtgcFlOrderDaoImpl.remove(delList);
			for (RtgcFlOrder rtgcFlOrder : list) {
				rtgcFlOrder.setAssignedPerson(user);
				rtgcFlOrder.setAssignedDate(new Date());
				bool = rtgcFlOrderDaoImpl.save(rtgcFlOrder);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return bool;
	}

	/**
	 * 派更返回
	 * 
	 * @param all
	 * @param delList
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	public boolean commitBack(RtgcFlPlanAll all, List<RtgcFlOrder> delList) {
		boolean bool = false;
		try {
			if (all != null) {
				bool = rtgcFlPlanAllDaoImpl.update(all);
				bool = rtgcFlOrderDaoImpl.remove(delList);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return bool;
	}

	/**
	 * 派更确认
	 * 
	 * @param user
	 * @param status
	 * @param list
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	public boolean cranesSure(User user, DataDict status,
			List<LinkedHashMap<String, Object>> list) {
		boolean bool = false;
		List<RtgcFlOrder> orderList = new ArrayList<RtgcFlOrder>();
		try {
			for (LinkedHashMap<String, Object> linkedHashMap : list) {
				List<RtgcFlOrder> list1 = search(linkedHashMap, null);
				double quantity = 0.0;
				for (RtgcFlOrder rtgcFlOrder : list1) {
					quantity += rtgcFlOrder.getWorkQuanHours();
					rtgcFlOrder.setStatus(status);
					rtgcFlOrder.setConfirmPerson(user);
					rtgcFlOrder.setConfirmDate(new Date());
					orderList.add(rtgcFlOrder);
				}
				RtgcFlOrder order = list1.get(0);
				String source = StringUtil.machToSource(order.getMachine().getDatacode());
				Profession profe = professionService.findByCode(order.getMachine().getDatavalue());
				DataDict dict = dataDictService.findByCode(source);
				BigDecimal deciaml = new BigDecimal(quantity);
				costService.createCost(order.getCompany().getCompanyId(), profe.getProfeid(), null, null, null, order
						.getOrderDate(), null, null, order.getOrderTime()
						.getDictid(), null, null, deciaml, dict.getDictid(),
						user);
			}
			bool = rtgcFlOrderDaoImpl.saveOrUpdate(orderList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return bool;
	}

	/**
	 * 派更确认返回
	 * 
	 * @param user
	 * @param status
	 * @param list
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	public boolean cranesSureBack(User user, DataDict status,
			List<LinkedHashMap<String, Object>> list) {
		boolean bool = false;
		List<RtgcFlOrder> orderList = new ArrayList<RtgcFlOrder>();
		try {
			for (LinkedHashMap<String, Object> linkedHashMap : list) {
				List<RtgcFlOrder> list1 = search(linkedHashMap, null);
				for (RtgcFlOrder rtgcFlOrder : list1) {
					rtgcFlOrder.setStatus(status);
					rtgcFlOrder.setReConfirmPerson(user);
					rtgcFlOrder.setReConfirmDate(new Date());
					orderList.add(rtgcFlOrder);
				}
			}
			bool = rtgcFlOrderDaoImpl.saveOrUpdate(orderList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return bool;
	}

	/**
	 * 计费返回派更确认
	 * 
	 * @param orderDate
	 *            订更日期
	 * @param orderTimeId
	 *            更次Id
	 * @param companyId
	 *            承包商Id
	 * @param sourceCode
	 *            工种Code
	 * @return
	 * @throws Exception 
	 * **/
	public boolean costback(Date orderDate, String orderTimeId, Long companyId,
			String sourceCode) throws Exception {
		boolean bool = false;
		String machineCode = "";
		if (sourceCode.equals(DictionaryUtils.DICT_CODE_COST_SOURCE_2)) {
			machineCode = DictionaryUtils.OPTIONTYPE_RTGC;
		} else if (sourceCode.equals(DictionaryUtils.DICT_CODE_COST_SOURCE_1)) {
			machineCode = DictionaryUtils.OPTIONTYPE_FL;
		}
		String queryString = "from RtgcFlOrder as c where c.orderDate = :orderDate and c.orderTime.dictid =:orderTimeId and c.company.companyId =:companyId and c.machine.datacode =:machineCode";
		if (orderDate != null && !"".equals(orderDate) && orderTimeId != null
				&& !"".equals(orderTimeId) && machineCode != null
				&& !"".equals(machineCode)) {
			HashMap<String, Object> valueMap = new HashMap<String, Object>();
			valueMap.put("orderDate", orderDate);
			valueMap.put("orderTimeId", orderTimeId);
			valueMap.put("companyId", companyId);
			valueMap.put("machineCode", machineCode);
			List<RtgcFlOrder> list = rtgcFlOrderDaoImpl.search(queryString,
					valueMap, null);
			if(list.size() == 0) throw new Exception("找不到派更确认数据");
			DataDict dict = dataDictService
					.findByCode(DictionaryUtils.ORDERSTATUS2);
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setStatus(dict);
			}
			bool = rtgcFlOrderDaoImpl.saveOrUpdate(list);
		}
		return bool;
	}
}
